{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '3'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dataset-bpe.json') as fopen:\n",
    "    data = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 2\n",
    "GO = 1\n",
    "vocab_size = 32000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = [i + [2] for i in train_Y]\n",
    "test_Y = [i + [2] for i in test_Y]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size, learning_rate,\n",
    "                beam_width = 5):\n",
    "        \n",
    "        def cells(size_layer = size_layer, reuse=False):\n",
    "            return tf.nn.rnn_cell.LSTMCell(size_layer,initializer=tf.orthogonal_initializer(),reuse=reuse)\n",
    "        \n",
    "        def attention(encoder_out, seq_len, reuse=False):\n",
    "            attention_mechanism = tf.contrib.seq2seq.BahdanauAttention(num_units = size_layer, \n",
    "                                                                    memory = encoder_out,\n",
    "                                                                    memory_sequence_length = seq_len)\n",
    "            return tf.contrib.seq2seq.AttentionWrapper(\n",
    "            cell = tf.nn.rnn_cell.MultiRNNCell([cells(reuse=reuse) for _ in range(num_layers)]), \n",
    "                attention_mechanism = attention_mechanism,\n",
    "                attention_layer_size = size_layer)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        \n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        embeddings = tf.Variable(tf.random_uniform([vocab_size, embedded_size], -1, 1))\n",
    "        encoder_out = tf.nn.embedding_lookup(embeddings, self.X)\n",
    "        \n",
    "        for n in range(num_layers):\n",
    "            (out_fw, out_bw), (state_fw, state_bw) = tf.nn.bidirectional_dynamic_rnn(\n",
    "                cell_fw = cells(size_layer // 2),\n",
    "                cell_bw = cells(size_layer // 2),\n",
    "                inputs = encoder_out,\n",
    "                sequence_length = self.X_seq_len,\n",
    "                dtype = tf.float32,\n",
    "                scope = 'bidirectional_rnn_%d'%(n))\n",
    "            encoder_out = tf.concat((out_fw, out_bw), 2)\n",
    "        bi_state_c = tf.concat((state_fw.c, state_bw.c), -1)\n",
    "        bi_state_h = tf.concat((state_fw.h, state_bw.h), -1)\n",
    "        bi_lstm_state = tf.nn.rnn_cell.LSTMStateTuple(c=bi_state_c, h=bi_state_h)\n",
    "        encoder_state = tuple([bi_lstm_state] * num_layers)\n",
    "        \n",
    "        main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        dense = tf.layers.Dense(vocab_size)\n",
    "        \n",
    "        with tf.variable_scope('decode'):\n",
    "            decoder_cells = attention(encoder_out, self.X_seq_len)\n",
    "            states = decoder_cells.zero_state(batch_size, tf.float32).clone(cell_state=encoder_state)\n",
    "\n",
    "            training_helper = tf.contrib.seq2seq.TrainingHelper(\n",
    "                    inputs = tf.nn.embedding_lookup(embeddings, decoder_input),\n",
    "                    sequence_length = self.Y_seq_len,\n",
    "                    time_major = False)\n",
    "            training_decoder = tf.contrib.seq2seq.BasicDecoder(\n",
    "                    cell = decoder_cells,\n",
    "                    helper = training_helper,\n",
    "                    initial_state = states,\n",
    "                    output_layer = dense)\n",
    "            training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                    decoder = training_decoder,\n",
    "                    impute_finished = True,\n",
    "                    maximum_iterations = tf.reduce_max(self.Y_seq_len))\n",
    "            self.training_logits = training_decoder_output.rnn_output\n",
    "        \n",
    "        with tf.variable_scope('decode', reuse=True):\n",
    "            encoder_out_tiled = tf.contrib.seq2seq.tile_batch(encoder_out, beam_width)\n",
    "            encoder_state_tiled = tf.contrib.seq2seq.tile_batch(encoder_state, beam_width)\n",
    "            X_seq_len_tiled = tf.contrib.seq2seq.tile_batch(self.X_seq_len, beam_width)\n",
    "            decoder_cell = attention(encoder_out_tiled, X_seq_len_tiled, reuse=True)\n",
    "            states = decoder_cell.zero_state(batch_size * beam_width, tf.float32).clone(\n",
    "                    cell_state = encoder_state_tiled)\n",
    "            predicting_decoder = tf.contrib.seq2seq.BeamSearchDecoder(\n",
    "                cell = decoder_cell,\n",
    "                embedding = embeddings,\n",
    "                start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),\n",
    "                end_token = EOS,\n",
    "                initial_state = states,\n",
    "                beam_width = beam_width,\n",
    "                output_layer = dense,\n",
    "                length_penalty_weight = 0.0)\n",
    "            predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                decoder = predicting_decoder,\n",
    "                impute_finished = False,\n",
    "                maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))\n",
    "            self.fast_result = predicting_decoder_output.predicted_ids[:, :, 0]\n",
    "        \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 512\n",
    "num_layers = 2\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "reduction_indices is deprecated, use axis instead\n",
      "WARNING:tensorflow:From <ipython-input-7-e9ba56a4cfee>:12: LSTMCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.LSTMCell, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-e9ba56a4cfee>:40: bidirectional_dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.Bidirectional(keras.layers.RNN(cell))`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:464: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:958: Layer.add_variable (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.add_weight` method instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:962: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:244: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n",
      "WARNING:tensorflow:From <ipython-input-7-e9ba56a4cfee>:19: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/contrib/seq2seq/python/ops/beam_search_decoder.py:971: to_int64 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, num_layers, embedded_size, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[23168, 23168, 23168, 31171, 31171, 13772, 13772, 13772, 12402,\n",
       "         12402, 12402, 12402, 28816, 28816, 28816, 28816, 28816, 28816,\n",
       "         20852, 20852, 15630,  6855,  6855,  6855,  6855,  6855,  6855,\n",
       "          6855,  2631,  2631, 17941, 17941, 19057, 19057, 15185, 15185,\n",
       "         15185, 16253, 16253, 16253, 16253, 16253, 16253, 31464, 31464,\n",
       "         31464, 31464, 31464, 31464, 22820, 22820, 22820, 10320, 10320,\n",
       "         10320, 10320, 20852, 17571, 17571, 17571, 17571, 21324, 21324,\n",
       "         21324, 21324, 26041, 26041, 26041, 26041, 24964, 24964,  8724],\n",
       "        [31956, 31956, 31956, 31956, 12856, 12856, 12856, 12856, 12856,\n",
       "         10310, 10310, 10310, 13742, 13742, 13742, 13742, 13742, 13742,\n",
       "         19381,  8841,  8841,  8841,  8841, 14559, 14559, 14559, 11446,\n",
       "         11446, 25518, 25518,   490,   490, 14940,  5620, 14940,  5620,\n",
       "          5620, 26876, 10891, 10891, 10891, 10891, 29976,  3148,  3148,\n",
       "          3148, 29976, 29976, 18657, 18941, 18657, 18657, 18657, 15270,\n",
       "         15270, 15270, 15270, 15270,  3141,  3141,  3141,  6794,  6794,\n",
       "          6794,  6794,  9298,  9298,  4277,  4277,  4277,  4277,  3935],\n",
       "        [30700, 30700,  9838,  4537,  4537, 25306, 25306, 25306, 25306,\n",
       "         25306, 25306, 16458, 16458, 16458, 16458, 17691, 17691, 17691,\n",
       "         17691, 17691, 15996, 30700, 30700, 30700, 30700, 30700, 30700,\n",
       "          8628, 23752, 23752, 23752, 23752, 23752, 23752, 23752, 23752,\n",
       "         16710, 16710, 16710, 24927, 24927, 24927,  6937,  6937,  6937,\n",
       "          6937,  6937, 13124, 13485, 13485, 13485, 13485, 13485, 13485,\n",
       "          1056,  1056,  1056,  1056,  1056,  1056, 18876, 18876, 25306,\n",
       "         25306, 25306, 25306, 25306, 25306,  9211,  9211, 14374, 14367],\n",
       "        [22232, 26545, 26545, 26545, 26545, 26545, 26545, 22309, 22309,\n",
       "         22309, 22309, 22309, 22309, 22309, 22309, 22309, 22309, 22309,\n",
       "         22309, 22309, 22309, 22309, 22309, 22309, 22309, 22309, 22309,\n",
       "         22309, 22309, 22309, 22309, 22309, 22309, 22309, 22309, 22309,\n",
       "         22309, 22309, 22309, 22309, 22309, 22309, 22309, 22309, 22309,\n",
       "         22309, 22309, 22309, 22309, 22309, 22309, 22309, 22309, 22309,\n",
       "         22309, 22309, 22309, 22309, 22309, 22309, 22309, 22309, 22309,\n",
       "         22309, 22309, 22309, 22309, 22309, 22309, 22309, 22309, 22309],\n",
       "        [ 9233, 29119, 29119,  4086,  4086,  4086,  4086,  4086,  4086,\n",
       "          4086,  4086,  4086,  4086, 19433,  4086, 19433,  4086,  4086,\n",
       "          4086,   483,   483,   483, 29214, 27277, 27277,  1474, 26773,\n",
       "         26773, 23656, 23385, 23656, 23656, 23385, 23656, 14694, 14694,\n",
       "         14694, 14694, 14694, 23670, 23670, 23670, 23670,  7375, 23907,\n",
       "         23907, 23907, 23907, 23907, 23907, 23907, 23907, 23907, 23907,\n",
       "         23907, 23907, 27572, 27572, 28252, 28252, 28252,  3308,  1600,\n",
       "          3308,  9259,  9259,  9259,  4020,  9259, 15117, 15117, 10397],\n",
       "        [ 9765,  9765,  9765,  9765, 20318, 20318, 20318, 20318, 23436,\n",
       "         23436, 20576, 20576, 20576, 20576, 22256, 22256, 13586, 13586,\n",
       "         13586, 13586, 28659, 28659, 22160, 19811, 19811, 19811, 19811,\n",
       "         19811, 17575, 31410, 31410, 31410,   581,   581,  1376,  1376,\n",
       "          1376, 17575, 22307, 22307, 22307, 22307, 31046, 31046, 31046,\n",
       "         10837, 10837,  6026,  6026,  6026,  6026,  6026, 11180, 28082,\n",
       "         28082, 28082, 28082, 15934, 15934, 15934, 23332, 23332, 23332,\n",
       "         23332, 20731, 26279, 26279, 26279, 26279, 26279, 14793, 14793],\n",
       "        [27139, 31243, 31243, 31243, 31243, 20726,  9794,  9794, 26647,\n",
       "          5955, 14632, 14632, 14632, 14632, 14632, 14632, 24522,  4873,\n",
       "          4873,  4873,  4873,  4873,  4873,  4873, 27048, 27048, 27048,\n",
       "         27048, 11336, 11336,  2809,  2809,  2809,  2809,  2809,  2809,\n",
       "          2809,  2809,  2714,  3417,  4873,  4873,  4873,  4873,  4873,\n",
       "         28355, 24167, 24167, 24167, 24167, 24167, 24167, 24167, 11758,\n",
       "         11758, 11758, 11758, 11758, 11758,  5805,  5805,  5805,  5805,\n",
       "          5805, 28355,  2605,  2605,  2605,  2605, 12759, 12759, 31347],\n",
       "        [  896,   896,   896,   896, 14334, 14334, 14334, 14334, 27482,\n",
       "         27482, 20071, 20071, 20071,   463,  1420,  1420,  1420,   898,\n",
       "           898,   898,  4042,  4042, 20850, 20850, 20850, 20850, 20850,\n",
       "         20850,   532,   532,   532,   532, 23266, 23266, 28902, 28902,\n",
       "         28902, 28902,  5029, 20438, 20438, 20438, 20438, 20438, 20438,\n",
       "         20438, 20438, 12948, 12948, 12948, 12948, 31497,  2623,  2623,\n",
       "          2623,  2623,  2623,  2623,  2623, 30020,  2623, 30020, 30020,\n",
       "         30020, 30020, 30020, 30020, 30020, 30020, 31828,  7368,  7368],\n",
       "        [ 4620,  4620,  4620,  4620,  4620, 10586, 10586,  4620, 10586,\n",
       "         10586, 10586, 10586, 10586, 10586,  6859,  6329, 19739, 19739,\n",
       "         19739, 19739, 19739, 19739, 19739, 13150, 13150, 13150, 13150,\n",
       "          6608, 27766, 27766, 22472, 22472, 22472,  5741,  5741,  3780,\n",
       "          3780, 14344, 14344, 14344, 14344, 14344,  4577,   221,   221,\n",
       "           221,   221,   221, 13980,   221, 23968, 23968, 23968, 23968,\n",
       "         23968, 23968, 23968, 23968, 23968, 13851, 23968, 11300, 23968,\n",
       "         11300, 16456, 16456, 16456, 16456,  4202, 21848, 18258, 18258],\n",
       "        [16804,   569,   569,   569,   569,     5,     5, 28030, 28030,\n",
       "         28030, 26793, 26793, 26793, 26793, 26793, 27082, 10313, 10313,\n",
       "         10313, 10313,  1867,  1867,  1867,  1867,  1867, 11674, 11674,\n",
       "         26866, 26866, 26866, 26866, 14886, 20792, 20792,     5,     5,\n",
       "             5,     5,     5,  1345,  1345, 25486, 25486, 25486, 15874,\n",
       "         15874, 15874, 15874, 15874, 15874, 15874, 15874, 15874, 15874,\n",
       "         15023, 15023, 10901, 10513, 10513, 10513, 10513, 10513, 10513,\n",
       "          7066,  7066,  7066,  7066,  7066, 18825, 18825, 18825, 18825]],\n",
       "       dtype=int32), 10.3733425, 0.0]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x = pad_sequences(train_X[:10], padding='post')\n",
    "batch_y = pad_sequences(train_Y[:10], padding='post')\n",
    "\n",
    "sess.run([model.fast_result, model.cost, model.accuracy], \n",
    "         feed_dict = {model.X: batch_x, model.Y: batch_y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:56<00:00,  1.87it/s, accuracy=0.388, cost=3.71]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.89it/s, accuracy=0.446, cost=3.2] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 4.930395, training avg acc 0.268477\n",
      "epoch 1, testing avg loss 3.544549, testing avg acc 0.407285\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:14<00:00,  1.83it/s, accuracy=0.507, cost=2.71]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.98it/s, accuracy=0.559, cost=2.47]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 3.092906, training avg acc 0.457319\n",
      "epoch 2, testing avg loss 2.876742, testing avg acc 0.486617\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:15<00:00,  1.83it/s, accuracy=0.569, cost=2.22]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.97it/s, accuracy=0.565, cost=2.21]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 2.537096, training avg acc 0.522487\n",
      "epoch 3, testing avg loss 2.663216, testing avg acc 0.511075\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:14<00:00,  1.83it/s, accuracy=0.63, cost=1.87] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.96it/s, accuracy=0.581, cost=2.08]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 2.218380, training avg acc 0.562552\n",
      "epoch 4, testing avg loss 2.563094, testing avg acc 0.527792\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:15<00:00,  1.83it/s, accuracy=0.662, cost=1.61]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.99it/s, accuracy=0.602, cost=2.09]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 1.985724, training avg acc 0.593927\n",
      "epoch 5, testing avg loss 2.556591, testing avg acc 0.531686\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:15<00:00,  1.83it/s, accuracy=0.707, cost=1.39]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.99it/s, accuracy=0.618, cost=2.15]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 1.800010, training avg acc 0.620613\n",
      "epoch 6, testing avg loss 2.568143, testing avg acc 0.533972\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:15<00:00,  1.83it/s, accuracy=0.727, cost=1.2] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.95it/s, accuracy=0.618, cost=2.07]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 1.645908, training avg acc 0.643907\n",
      "epoch 7, testing avg loss 2.622346, testing avg acc 0.536611\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:14<00:00,  1.83it/s, accuracy=0.746, cost=1.08]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.96it/s, accuracy=0.597, cost=2.27]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 1.513447, training avg acc 0.664674\n",
      "epoch 8, testing avg loss 2.721978, testing avg acc 0.529597\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:14<00:00,  1.83it/s, accuracy=0.776, cost=0.948]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.98it/s, accuracy=0.57, cost=2.38] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 1.395319, training avg acc 0.684007\n",
      "epoch 9, testing avg loss 2.787175, testing avg acc 0.526358\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:14<00:00,  1.83it/s, accuracy=0.798, cost=0.841]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.99it/s, accuracy=0.554, cost=2.48]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 1.288003, training avg acc 0.702190\n",
      "epoch 10, testing avg loss 2.902014, testing avg acc 0.518718\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:15<00:00,  1.83it/s, accuracy=0.809, cost=0.763]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.98it/s, accuracy=0.575, cost=2.48]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 1.194369, training avg acc 0.718522\n",
      "epoch 11, testing avg loss 3.000577, testing avg acc 0.516481\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:14<00:00,  1.83it/s, accuracy=0.835, cost=0.679]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.98it/s, accuracy=0.57, cost=2.52] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 1.111355, training avg acc 0.733295\n",
      "epoch 12, testing avg loss 3.058266, testing avg acc 0.521441\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:14<00:00,  1.83it/s, accuracy=0.853, cost=0.591]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.97it/s, accuracy=0.575, cost=2.63]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 1.045526, training avg acc 0.744615\n",
      "epoch 13, testing avg loss 3.136143, testing avg acc 0.517302\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:15<00:00,  1.83it/s, accuracy=0.857, cost=0.545]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.99it/s, accuracy=0.548, cost=2.65]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 0.982015, training avg acc 0.756470\n",
      "epoch 14, testing avg loss 3.237216, testing avg acc 0.514300\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:15<00:00,  1.83it/s, accuracy=0.861, cost=0.516]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.98it/s, accuracy=0.57, cost=2.75] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 0.923610, training avg acc 0.767492\n",
      "epoch 15, testing avg loss 3.345384, testing avg acc 0.511940\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop:  65%|██████▌   | 1017/1563 [09:11<05:41,  1.60it/s, accuracy=0.783, cost=0.858]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "minibatch loop: 100%|██████████| 1563/1563 [14:14<00:00,  1.83it/s, accuracy=0.89, cost=0.406] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.95it/s, accuracy=0.575, cost=2.88]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 0.786432, training avg acc 0.793934\n",
      "epoch 18, testing avg loss 3.617091, testing avg acc 0.507661\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop:  28%|██▊       | 434/1563 [03:54<10:48,  1.74it/s, accuracy=0.809, cost=0.722]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "minibatch loop: 100%|██████████| 1563/1563 [14:12<00:00,  1.83it/s, accuracy=0.9, cost=0.358]  \n",
      "minibatch loop: 100%|██████████| 40/40 [00:09<00:00,  4.05it/s, accuracy=0.538, cost=3.17]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 0.718653, training avg acc 0.807489\n",
      "epoch 20, testing avg loss 3.804664, testing avg acc 0.501345\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x = pad_sequences(train_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import bleu_hook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 40/40 [00:27<00:00,  1.45it/s]\n"
     ]
    }
   ],
   "source": [
    "results = []\n",
    "for i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "    feed = {model.X: batch_x}\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 3])\n",
    "    results.extend(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.19480321"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
